<?php

namespace App\Console\Commands;

use App\Console\Commands\Common\CommonCommand;
use App\Models\Order\Order;
use App\Models\Rbac\Permission;
use App\Models\Repair\RepairFactory;
use App\Models\User\User;
use EasyWeChat\Factory;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Ocr\V20181119\Models\TableOCRRequest;
use TencentCloud\Ocr\V20181119\OcrClient;

class Demo extends CommonCommand {


    public function tencentSDK() {
        $imgUlr = "https://bjyoupei.techbz.cn/storage/upload/order/1.jpg";
        $cert = new Credential(env('TENCENT_SECRET_ID'), env('TENCENT_SECRET_KEY'));

        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint('ocr.tencentcloudapi.com');

        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);

        $tableOCRRequest = new TableOCRRequest();
        $tableOCRRequest->setImageUrl($imgUlr);

        $client = new OcrClient($cert,'ap-beijing',$clientProfile);
        $res = $client->TableOCR($tableOCRRequest);

        Log::info('res',json_decode($res->toJsonString(),true));
        Log::info('res',$res->getTextDetections());
        Log::info('res',array_column($res->getTextDetections(), 'Text'));

        /*$params=[
            'ImageUrl'=>'http://bjyoupei/storage/upload/order/1.jpg',
        ];*/
    }


    public function handle() {


       dd(Str::length('鲁QG098R'));



        /*$code = '081LT6100GixDO17vH100ul5Sd3LT61m';
        $user = $app->oauth->userFromCode($code);
        dump($user,'----------');
        dd($user['token_response']['openid']);*/



        //$order = Order::where(['id'=>1])->first();

        //$order->compareOcr();


       /* $config = config('wechat.default');
        $app = Factory::miniProgram($config);
        $user = User::where('id',1)->first();
        //$smallOpenId = $user->wx_samll_open_id??null;
        $smallOpenId = "obCPf5AyttvVVcfkr7LFsFr63ANY";
        $template_id = "E1uJnAkLX8vwYngFDWyb3xxzGgV7KB5tWg_WT6lU7Hs";
        $data = [
            'template_id' => $template_id, // 所需下发的订阅模板id
            'touser' => $smallOpenId,     // 接收者（用户）的 openid
            'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'phrase2' => [
                    'value' => '已通过',
                ],
                'car_number3' => [
                    'value' => '鲁QGE639',
                ],
                'thing4' => [
                    'value' => '您的订单已审核通过，请尽快选择自主维修或指定维修',
                ],
            ],
        ];
        $app->subscribe_message->send($data);*/

        /*$phone = '15762098859';
        $template= 'SMS_251695573';
        $verifyCode =0;
        sendSms($phone,$template,$verifyCode);*/

        //dd(generateJWT(['id'=>14,'time'=>time()]));


        /*dd(User::where(['phone'=>15762098859])->exists());


        $key = "DDJBZ-W6XW6-3VESU-EYQWU-4XZH7-OIFI7";
        $cityCode = 371300;
        $lat = 35.129154;
        $lng = 118.314301;
        $factories = [];
        RepairFactory::where('city_code',$cityCode)
            ->where('status',1)
            ->chunk(2,function ($records) use ($lat,$lng,$key,&$factories){
                $points = [];
                foreach ($records as $record) {
                    $points[] = $record->lat.",".$record->lng;
                }
                $from = $lat.",".$lng;
                $to = implode(';', $points);
                $mode = "driving";
                $url = "https://apis.map.qq.com/ws/distance/v1/matrix?key=$key&from=$from&to=$to&mode=$mode";
                $res = makeRequest($url);
                Log::info('url:'.$url);
                Log::info('res:',$res);
                $distanceInfo = json_decode($res['result'],true)['result']['rows'][0]['elements'];
                foreach ($records as $k=>$record) {
                    $record->distance = ($distanceInfo[$k]['distance']/1000);
                    $record->business_time = $record->business_s_time.' - '. $record->business_e_time;
                    $record->cover_url = Arr::first(explode(',', $record->imgs));
                }
                $factories = array_merge($factories,$records->toArray());
                Log::info('factories',$factories);
            });
        array_multisort(array_column($factories, 'distance'), SORT_ASC, $factories);
        foreach ($factories as $record) {
            $record['distance'] .= 'km';
        }
        dump($factories);*/

    }

    protected function get_url($url, $post_data=[]){
        //请求头配置
        $headers = array(
            "host:recognition.image.myqcloud.com",
            "content-type:application/json",
            "authorization:".getTencentSign()['signStr'], //鉴权算法 下方查看
            "X-TC-Action:RecognizeTableOCR",
            "X-TC-Version:2018-11-19",
            "X-TC-Timestamp:".time(),
            "X-TC-Region:ap-beijing",
        );
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt($curl, CURLOPT_POST, true);
        //curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }

    public function handle1() {

        $temp = [];
        $points = RepairFactory::get(['lat','lng']);
        foreach ($points as $point) {
            $temp[] = $point->lat.",".$point->lng;
        }




        $lat = "35.05151";
        $lng = "118.34787";
        $key = "DDJBZ-W6XW6-3VESU-EYQWU-4XZH7-OIFI7";
        $from = $lat.",".$lng;
        $to = implode(';', $temp);
        $mode = "driving";

        $url = "https://apis.map.qq.com/ws/distance/v1/matrix?key=$key&from=$from&to=$to&mode=$mode";


        //$ip = "221.2.72.218";
        //$url = "https://apis.map.qq.com/ws/location/v1/ip?key=$key&ip=$ip";


        dump(makeRequest($url));

        return 0;
    }
}
